package com.docjohnson.pamphlet.activities;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.WeakHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.docjohnson.pamphlet.R;
import com.docjohnson.pamphlet.dialogs.Dialogs;
import com.docjohnson.pamphlet.models.Pamphlet;
import com.docjohnson.pamphlet.utils.PamphletPreferences;
import com.docjohnson.pamphlet.utils.Utils;

@SuppressLint("NewApi")
public class DashboardActivity extends DefaultActivity implements View.OnTouchListener, AdapterView.OnItemClickListener {

	private static final String TAG = DashboardActivity.class.getSimpleName();
	
	protected PamphletPreferences mPreferences;
	protected GridView mGridView;
	protected LinearLayout dashboardLayout;
	protected List<Pamphlet> pamphletList;
	protected Timer mTimer;
	private PamphletAdapter adapter = null;
	private RelativeLayout animationLayout = null;
	private ImageView animationImageView = null;
	private int selectedViewX = 0;
	private int selectedViewY = 0;
	private long lastClickTime = 0;
	int mIndex;

	private long timerStart = System.currentTimeMillis();
	private long screenSaverDelay;
	private boolean itemSelected = false;

	private View lastSelectedView = null;

	enum MODE {
		LOADING, NORMAL,
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dashboard);

		animationLayout = (RelativeLayout) findViewById(R.id.animationLayout);
		animationImageView = (ImageView) findViewById(R.id.pamphlet_animation_background);

		init();
	}

	private void init() {
		setlayouts();
		startTimer();
		getPamphlets();
	}

	private void setlayouts() {
		// mProvider = new PamphletProvider(this);
		mGridView = (GridView) findViewById(R.id.gridViewId);
		dashboardLayout = (LinearLayout) findViewById(R.id.dashboardLayoutId);

		mGridView.setOnItemClickListener(this);
		dashboardLayout.setOnTouchListener(this);

		mPreferences = new PamphletPreferences(this);
		pamphletList = new ArrayList<Pamphlet>();

	}

	ScheduledExecutorService service;
	
	private final Runnable startScreenSaver = new Runnable() {
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				public void run() {
					if (!isFinishing() && System.currentTimeMillis() - lastClickTime >= screenSaverDelay)
						startScreenSaver();
				}
			});
		}
	};
	
	private void startTimer() {
		Log.d(TAG, "startTimer");
		screenSaverDelay = mPreferences.getScreenSaverDelay();
		try {
			service = Executors.newSingleThreadScheduledExecutor();
			service.schedule(startScreenSaver, screenSaverDelay, TimeUnit.MILLISECONDS);
			service.shutdown();
		} catch (RejectedExecutionException e) {
			e.printStackTrace();
		}
	}

	private void stopTimer() {
		Log.d(TAG, "stopTimer");
		service.shutdownNow();
	}

	@Override
	public boolean onTouch(View view, MotionEvent motionEvent) {
		timerStart = System.currentTimeMillis();
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case SCREEN_SAVER_REQUEST_CODE:
			if (resultCode == Activity.RESULT_OK)
				timerStart = System.currentTimeMillis();
			break;
		case PAMPHLET_DETAILS_REQUEST_CODE:
			if (resultCode == Activity.RESULT_OK)
				timerStart = System.currentTimeMillis();
			if (Build.VERSION.SDK_INT > 11) {
				animationImageView.animate().translationX(selectedViewX).translationY(selectedViewY).scaleX(1).scaleY(1).setDuration(500).setListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator animation) {

					}

					@Override
					public void onAnimationRepeat(Animator animation) {

					}

					@Override
					public void onAnimationEnd(Animator animation) {
						animationImageView.setVisibility(View.INVISIBLE);
						if(lastSelectedView != null)
							lastSelectedView.setVisibility(View.VISIBLE);
						itemSelected = false;
					}

					@Override
					public void onAnimationCancel(Animator animation) {

					}
				}).start();
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		startTimer();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		stopTimer();
	}

	private void getPamphlets() {
		Dialogs.showProgressDialog(this);
		try {
			Drawable drawable = Drawable.createFromPath(mPreferences.getDashboardImage());
			dashboardLayout.setBackgroundDrawable(drawable);
			final String pamplets = mPreferences.getPamphlets();
			JSONArray pamphletsJson = new JSONArray(pamplets);
			int count = pamphletsJson.length();

			Pamphlet[] pamphlets = new Pamphlet[count];
			for (int i = 0; i < count; ++i) {
				pamphlets[i] = new Pamphlet(pamphletsJson.getJSONObject(i));
			}

			pamphletList = Arrays.asList(pamphlets);

			adapter = new PamphletAdapter(this, pamphletList);
			mGridView.setAdapter(adapter);
			Dialogs.closeProgressDialog(this);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
		if (itemSelected) {
			return;
		}
		stopTimer();
		itemSelected = true;
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		final int displayHeight = (int) (displaymetrics.heightPixels);
		final int displayWidth = (int) (displaymetrics.widthPixels);
		int[] viewPosition = new int[2];
		view.getLocationOnScreen(viewPosition);
		selectedViewX = viewPosition[0];
		selectedViewY = viewPosition[1];
		animationImageView.setImageBitmap(adapter.getBitmapOfPamphlet(i));
		RelativeLayout.LayoutParams imageViewLayoutParams = (LayoutParams) animationImageView.getLayoutParams();
		imageViewLayoutParams.width = view.getWidth();
		imageViewLayoutParams.height = view.getHeight();
		animationImageView.setLayoutParams(imageViewLayoutParams);
		final float scaleSizeX = (displayWidth - Utils.dipToPixel(200, getResources())) / (3 * view.getWidth());
		final float scaleSizeY = (displayHeight - Utils.dipToPixel(80, getResources())) / (view.getHeight());
		if (Build.VERSION.SDK_INT > 11) {
			lastSelectedView = view;
			animationImageView.animate().translationX(0).translationY(0).setDuration(0).setListener(null).start();
			animationImageView.animate().setDuration(0).translationX(viewPosition[0]).translationY(viewPosition[1]).setListener(new AnimatorListener() {

				@Override
				public void onAnimationStart(Animator animation) {

				}

				@Override
				public void onAnimationRepeat(Animator animation) {

				}

				@Override
				public void onAnimationEnd(Animator animation) {
					lastClickTime = System.currentTimeMillis();
					animationImageView.setVisibility(View.VISIBLE);
					lastSelectedView.setVisibility(View.INVISIBLE);
					animationImageView.animate().setDuration(500).translationX(100 + (displayWidth - Utils.dipToPixel(200, getResources())) / 3 + ((displayWidth - Utils.dipToPixel(200, getResources())) / 3 - lastSelectedView.getWidth()) / 2).translationY(40 + (displayHeight - Utils.dipToPixel(80, getResources()) - lastSelectedView.getHeight()) / 2).scaleX(scaleSizeX).scaleY(scaleSizeY).setListener(new AnimatorListener() {

						@Override
						public void onAnimationStart(Animator animation) {
						}

						@Override
						public void onAnimationRepeat(Animator animation) {
						}

						@Override
						public void onAnimationEnd(Animator animation) {
							openPamphlet(i);
						}

						@Override
						public void onAnimationCancel(Animator animation) {

						}
					});
				}

				@Override
				public void onAnimationCancel(Animator animation) {

				}
			});
		} else {
			openPamphlet(i);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		stopTimer();
	}

	private void openPamphlet(final int index) {
		Intent intent = new Intent(this, PamphletDetailsActivity.class);
		intent.putExtra("pamphlet", pamphletList.get(index));
		startActivityForResult(intent, PAMPHLET_DETAILS_REQUEST_CODE);
	}

	private class PamphletAdapter extends BaseAdapter {
		private Context mContext;
		private List<Pamphlet> pamphlets;
		private WeakHashMap<String, Bitmap> pamphletBackgroundBitmaps = new WeakHashMap<String, Bitmap>();

		public PamphletAdapter(final Context context, List<Pamphlet> pamphlets) {
			mContext = context;
			this.pamphlets = pamphlets;
		}

		public int getCount() {
			return pamphlets.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int i, View view, ViewGroup viewGroup) {
			ImageView imageView;
			if (view == null) {
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams(148, 300));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//				imageView.setPadding(5, 35, 5, 5);
			} else {
				imageView = (ImageView) view;
			}
			if (!pamphletBackgroundBitmaps.containsKey(pamphlets.get(i).getLocalImagePath())) {
				BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
				bmpOptions.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(pamphlets.get(i).getLocalImagePath(), bmpOptions);
				int bmpHeight = bmpOptions.outHeight;
				bmpOptions.inJustDecodeBounds = false;
				bmpOptions.inSampleSize = bmpHeight/500;
				pamphletList.get(i).inSampleSize =  bmpHeight/500;
				pamphletBackgroundBitmaps.put(pamphlets.get(i).getLocalImagePath(), BitmapFactory.decodeFile(pamphlets.get(i).getLocalImagePath(), bmpOptions));
			}
			Bitmap bmp = pamphletBackgroundBitmaps.get((pamphlets.get(i).getLocalImagePath()));
			imageView.setImageBitmap(bmp);

			return imageView;
		}

		public Bitmap getBitmapOfPamphlet(int id) {
			return pamphletBackgroundBitmaps.get((pamphlets.get(id).getLocalImagePath()));
		}

		@Override
		public int getViewTypeCount() {
			return super.getViewTypeCount();
		}
	}
}